import React, {useRef, useState, useEffect} from "react";
import {
    StyleSheet,
    Text,
    TouchableOpacity,
    View,
    FlatList, ScrollView, Platform
} from "react-native";
import {LineChart} from "react-native-chart-kit";
import {colors, windowWidth} from "../../utils/config";
import {useStatisticsEvents} from "../../hooks/useStatisticsEvents";
import LevelEventsView from "../../components/LevelEvents";
import EventsModal from "../../components/EventsModal";
import CalendarView from "../../components/CalendarView";
import {getTodayAndSixDaysAgoDate} from "../../utils/utils";
import EmptyView from "../../components/EmptyView";
import {ArrowBackIcon, NativeBaseProvider} from "native-base";
import * as S from "../Home/styles";
import SkeletonView from "../../components/Skeleton";
import {showToast} from "../../utils/toast";

const date = getTodayAndSixDaysAgoDate();

const EventsChart = (props) => {

    const [eventsData, setEventsData] = useState([]);
    const [events, setEvents] = useState([]);
    const [maxTime, setMaxTime] = useState(100);
    const [ selectDateType, setSelectDateType ] = useState('YEAR');
    const [dateTimeWithoutYear, setDateTimeWithoutYear] = useState([]);
    const [ selectPeriod, setSelectPeriod, ] = useState(false);
    const { loadStatisticsEventsData,eventObj } = useStatisticsEvents();
    const [ startDate, setStartDate ] = useState(date.dateTime[0]);
    const [ endDate, setEndDate ] = useState(date.dateTime[1]);
    const [loading, setLoading] = useState(Object.keys(eventObj).length > 0 );

    const levelViewRef = useRef(null);
    const calendarViewRef = useRef(null);
    const eventsModalRef = useRef(null);
    const lock = useRef(false);
    useEffect(() => {
        if (!lock.current) {
            lock.current = true;
            setDateTimeWithoutYear([date.dateTimeWithOutYear[0].split('-').join('.'),date.dateTimeWithOutYear[1].split('-').join('.')]);
            if (Object.keys(eventObj).length === 0) {
                clickModal();
                showToast("error", "提示", '请先选择事件');
            }
        }
    }, []);

    const Title = ({navigation}:any)=>{
        return(
            <View style={styles.titleBox}>
                <TouchableOpacity
                    style={styles.backBtn}
                    onPress={() => {
                        navigation.goBack()
                    }}
                >
                    <ArrowBackIcon size="5" />
                </TouchableOpacity>
                {customHeader()}
                {/*<Text style={styles.titlText}>时间规划师</Text>*/}
            </View>
        )
    }

    const customHeader = () => {
        return (
            <TouchableOpacity style={styles.headerView} onPress={clickModal}>
                <Text style={styles.headerText}>选择事件</Text>
                <View style={styles.downArrow}></View>
            </TouchableOpacity>
        )
    }

    const getStatisticsEventsData = (eventsParam,dateType,startDateParam,endDateParam) => {
        if (eventsParam && eventsParam.length > 0 && startDateParam && endDateParam) {
            let params = {
                events: eventsParam,
                type: dateType,
                startDate: startDateParam,
                endDate: endDateParam,
            }
            console.log('--loadChartEventData---params---',params)
            loadStatisticsEventsData(params).then(function (res) {
                console.log('--loadStatisticsEventsData---res---',res)
                if (res.code === 0) {
                    setEventsData(res?.data.events || []);
                    setMaxTime(res?.data?.maxTime || 100);
                    setLoading(false);
                }
            });
        }
    }

    const clickModal = () => {
        eventsModalRef?.current?.showModal();
    }

    let datasets = [];
    let legend = [];
    let labels = [];
    let listData = [];
    let filterValue = [];

    if (eventsData.length>0) {

        for (let i = 0;i < eventsData[0]?.children?.length;i++) {
            let listItem = [];
            let usedTimeItem = [];
            eventsData.map((item,index)=>{
                if (item?.children.length > 0 && i < item?.children.length) {
                    listItem.push(item?.children[i]);
                    usedTimeItem.push(item?.children[i].usedTime);
                }
            })
            filterValue.push(usedTimeItem);
            listData.push(listItem);
        }

        for (let i = 0;i < eventsData[0]?.children?.length;i++) {
            datasets.push({
                key: 'datasets_'+i,
                data: filterValue[i],
                color: () => colors[i % colors.length], // optional
                strokeWidth: 2 // optional
            })
        }

        eventsData.map((item,index)=>{
            // const filterValue = (item?.children || []).map(i=>i.usedTime);
            // for (let i = 0;i < events.length;i++) {
            //     if (item?.children.length > 0 && i < item?.children.length) {
            //         filterValue.push()
            //     }
            // }
            // datasets.push({
            //     data: [5,2,1,3,4,5,6,9,1],
            //     // data: filterValue,
            //     color: () => colors[index % colors.length], // optional
            //     strokeWidth: 2 // optional
            // })
            labels.push(item.name);
            // legend.push(item.name);
        })
    }
    console.log('----eventchart--111--',datasets,'events:',events,'labels:',labels,'listData:',listData,'filterValue:',filterValue)

    const chartData = {
        labels: labels, //横坐标
        datasets: datasets,
        // legend: legend  头部标题
    };

    const chartConfig = {
        backgroundGradientFrom: '#fff',
        backgroundGradientTo: '#fff',
        decimalPlaces: 2, // optional, defaults to 2dp
        color: (opacity = 1) => `rgba(0, 0, 0, ${opacity})`,
        labelColor: (opacity = 1) => `rgba(0, 0, 0, ${opacity})`,
        style: {
            borderRadius: 16
        },
        propsForDots: {
            r: '4',
            strokeWidth: '2',
            // fill: 'transparent',
            stroke: colors[0] //边框颜色
        },
    };


    const renderItem = ({ item, index }) => {
        return (
            <View style={styles.detailsItem}>
                <Text style={styles.detailsTitle}>{item.name}</Text>
                {
                    item.children.map((child,j)=>{
                        return(
                            <View style={styles.detailsItemView} key={'eventChild_'+j}>
                                <View style={styles.detailsItemTopView}>
                                    <Text style={styles.detailsItemTopText}>{child.name}</Text>
                                    <Text style={styles.detailsItemTopText}>{child.usedTime}h</Text>
                                </View>
                                <View style={styles.detailsItemTopView}>
                                    <View style={styles.detailsItemPercentView}>
                                        <View style={[
                                            styles.detailsItemPercentView,
                                            {
                                                width: `${((child.usedTime||0)/maxTime.toFixed(2)*100)}%`,
                                                backgroundColor: colors[j % colors.length]
                                            },
                                            ]}>
                                        </View>
                                    </View>
                                    {/*<Text style={styles.detailsItemPercentValue}>{((item.usedTime||0)/maxTime.toFixed(2)*100)}%</Text>*/}
                                </View>
                            </View>
                        )
                    })
                }
            </View>
        );
    }

    let lineChartWidth = labels.length*40;
    if (lineChartWidth < windowWidth-32) {
        lineChartWidth = windowWidth-32;
    }

    const clickClear = (i) => {
        let newEventsData = [];
        eventsData.map((item)=>{
            item.children.splice(i,1);
            newEventsData.push(item);
        })
        if (newEventsData.length > 0 && newEventsData[0].children.length === 0) {
            newEventsData = [];
        }
        setEventsData(JSON.parse(JSON.stringify(newEventsData)));
    }

    const renderHeader = () => {
        return (
            <View>
                {
                    listData.map((item,i)=>{
                        let timeTotal = 0;
                        let averageTime = 0;
                        item.map((seg)=>{
                            timeTotal += seg.usedTime;
                            averageTime += seg.averageTime;
                        })
                        return (
                            <View style={styles.timeListView} key={'timeHeader_'+i}>
                                <View style={styles.timeLeftView}>
                                    <View style={[styles.dotView,{backgroundColor: colors[i % colors.length]}]}></View>
                                    <Text style={[styles.timeLeftTitle,{color: colors[i % colors.length]}]}>{item && item[0] && item[0]?.name}</Text>
                                </View>
                                <Text style={styles.timeTotalText}>总{timeTotal.toFixed(1)}h</Text>
                                <View style={styles.timeRightView}>
                                    <Text style={styles.timeAverageText}>平均{averageTime.toFixed(1)}小时</Text>
                                    <TouchableOpacity style={styles.timeClearView} onPress={()=>{
                                        clickClear(i);
                                    }}>
                                        <Text style={styles.timeClearText}>x</Text>
                                    </TouchableOpacity>
                                </View>
                            </View>
                        )
                    })
                }
                {
                    datasets.length>0?
                        <ScrollView bounces={false} horizontal={true} showsHorizontalScrollIndicator={false}>
                            <LineChart
                                data={chartData}
                                width={lineChartWidth}
                                height={220}
                                chartConfig={chartConfig}
                                bezier
                                style={styles.lineChartView}
                            />
                        </ScrollView>
                         : null
                }
                {
                    eventsData.length > 0 ? <Text style={styles.eventsTitleText}>事件详细时长</Text> : null
                }

            </View>
        )
    }

    const renderEmptyComponent = () => {
        return <EmptyView/>;
    }

    console.log('----eventchart--eventsData--',eventsData,'datasets:',datasets,'legend:',legend,'maxTime:',maxTime)

    return (
        <S.GrayContainer>
            <NativeBaseProvider >
                <View style={styles.container}>
                    <Title navigation={props?.navigation}/>
                    <LevelEventsView
                        from={'eventsChart'}
                        ref={levelViewRef}
                        selectPeriod = {selectPeriod}
                        dateTimeWithoutYear = {dateTimeWithoutYear}
                        dateCallback={(startDateParam,endDateParam) => {
                            setStartDate(startDateParam);
                            setEndDate(endDateParam);
                        }}
                        periodCallback={(type) => {
                            setSelectPeriod(type);
                        }}
                        clickPeriodDate={() => {
                            calendarViewRef?.current?.toggleModal();
                        }}
                        loadCallback={(parentId,level,dateType,startDateParam,endDateParam)=>{
                            console.log('---loadCallback--levelevents-',parentId,level,dateType,startDateParam,endDateParam)
                            setSelectDateType(dateType);
                            setStartDate(startDateParam);
                            setEndDate(endDateParam);
                            if (events.length > 0) {
                                getStatisticsEventsData(events,dateType,startDateParam,endDateParam);
                            } else if (Object.keys(eventObj).length > 0) {
                                let tmpEvents = [];
                                Object.keys(eventObj).map((key)=>{
                                    tmpEvents.push({
                                        id: key,
                                        level: eventObj[key].level
                                    })
                                })
                                setEvents(tmpEvents);
                                getStatisticsEventsData(tmpEvents,dateType,startDateParam,endDateParam);
                            }
                        }}
                    />
                    {
                        loading > 0?
                            <SkeletonView/>
                            :
                            <FlatList
                                data={eventsData}
                                style={{ flex: 1}}
                                renderItem={renderItem}
                                keyExtractor={(item,index) => "calculate_"+index}
                                showsVerticalScrollIndicator={false}
                                ListEmptyComponent={renderEmptyComponent}
                                ListHeaderComponent={renderHeader}
                            />
                    }
                    <EventsModal
                        ref={eventsModalRef}
                        callback={(events)=>{
                            setEvents(events);
                            getStatisticsEventsData(events,selectDateType,startDate,endDate);
                        }}
                    />

                    <CalendarView
                        ref={calendarViewRef}
                        selectPeriod
                        selectedRangeCallback={(period)=>{
                            if (period.length === 2) {
                                let newDateBeforeSevenDay = period[0].split('-');
                                newDateBeforeSevenDay.splice(0,1);
                                let newCurrentDay = period[1].split('-');
                                newCurrentDay.splice(0,1);
                                setDateTimeWithoutYear([newDateBeforeSevenDay.join('.'),newCurrentDay.join('.')]);
                                setSelectPeriod(true);
                                getStatisticsEventsData(events,selectDateType,period[0],period[1]);
                            }
                        }}
                    />

                </View>
            </NativeBaseProvider>
        </S.GrayContainer>
    );
};

export default EventsChart;

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    timeListView: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        backgroundColor: 'rgba(232, 232, 232, 1)',
        height: 32,
        borderRadius: 8,
        marginBottom: 5,
        marginHorizontal: 16,
        paddingLeft: 16,
        paddingRight: 10,
    },
    timeLeftView: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    dotView: {
        width: 4,
        height: 4,
        borderRadius: 2,
    },
    timeLeftTitle: {
        fontSize: 12,
        marginLeft: 10,
        width: 100,
    },
    timeTotalText: {
        color: 'rgba(72, 72, 74, 1)',
        fontSize: 12,
        width: 100,
        textAlign: 'left',
    },
    timeRightView: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    timeAverageText: {
        color: 'rgba(72, 72, 74, 1)',
        fontSize: 12,
        textAlign: 'right',
    },
    timeClearView: {
        paddingHorizontal: 5,
        marginLeft: 10,
    },
    timeClearText: {
        color: 'rgba(72, 72, 74, 1)',
        fontSize: 14,
    },
    lineChartView: {
        marginTop: 16,
        borderRadius: 16,
        marginHorizontal: 16,
        minWidth: windowWidth - 32,
    },
    detailsItem: {
        backgroundColor: '#fff',
        borderRadius: 16,
        marginHorizontal: 16,
        paddingHorizontal: 16,
        paddingBottom: 16,
        paddingTop: 12,
        marginBottom: 16,
    },
    detailsTitle: {
        color: 'rgba(72, 72, 74, 1)',
        fontSize: 14,
        marginBottom: 8,
    },
    detailsItemView: {
        backgroundColor: 'rgba(247, 247, 247, 1)',
        borderRadius: 16,
        marginBottom: 2,
        paddingHorizontal: 16,
        paddingVertical: 12,
    },
    detailsItemTopView: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
    },
    eventsTitleText: {
        marginTop: 16,
        marginBottom: 8,
        marginLeft: 16,
        fontSize: 14,
        color: 'rgba(142, 142, 147, 1)',
    },
    detailsItemTopText: {
        marginBottom: 8,
        fontSize: 14,
        color: 'rgba(72, 72, 74, 1)',
    },
    detailsItemPercentView: {
        backgroundColor: 'rgba(229, 229, 234, 1)',
        height: 6,
        borderRadius: 3,
        flex: 1,
    },
    detailsItemPercentValue: {
        color: 'rgba(142, 142, 147, 1)',
        fontSize: 14,
        width: 50,
        textAlign: 'right',
    },
    headerView: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    headerText: {
        color: 'rgba(0, 0, 0, 0.9)',
        fontSize: 18,
        fontWeight: 'bold',
    },
    downArrow: {
        width: 0,
        height: 0,
        borderLeftWidth: 7,
        borderRightWidth: 7,
        borderTopWidth: 7,
        borderStyle: 'solid',
        borderLeftColor: 'transparent',
        borderRightColor: 'transparent',
        borderBottomColor: 'black',
        opacity: 0.5,
        marginLeft: 5,
    },
    titleBox:{
        width:'100%',
        position:'relative',
        alignItems:'center',
        height:40,
        justifyContent:"center",
        marginBottom:16,
        paddingHorizontal: 16,
    },
    backBtn:{
        position:'absolute',
        left:16,
        backgroundColor:'#fff',
        width:40,
        height:40,
        display:'flex',
        alignItems:'center',
        justifyContent:'center',
        borderRadius:100,

        shadowColor: Platform.OS === 'android' ? '' : 'rgba(0, 0, 0, 0.08)', // 阴影颜色
        shadowOffset: { width: 0, height: 2 }, // 阴影偏移
        shadowOpacity: 1, // 阴影不透明度
        shadowRadius: 8, // 阴影半径
        elevation: 3, // 阴影深度
    },
    titlText:{
        fontSize:16,
        fontWeight:'600',
        color:'#000000'
    },
});